<?php

namespace Ignus\View\Extension;

use Ignus\View\Node;
use Ignus\View\Markup;
use Ignus\View\Token;
use Ignus\View\Parser;
use Ignus\View\Environment;
use Ignus\View\Extension;
use Ignus\View\ExpressionParser;
use Ignus\View\Node\Expression\Test;
use Ignus\View\Node\Expression\Constant;

use Ignus\View\Functions\Func;
use Ignus\View\Filter\FunctionFilter;
use Ignus\View\Filter\Method;

use Ignus\View\Error\Runtime;

use Ignus\View\Test\FunctionTest;

if (!defined('ENT_SUBSTITUTE')) {
    define('ENT_SUBSTITUTE', 8);
}

class Core extends Extension
{
    /**
     * @return \Ignus\View\TokenParser[]
     */
    public function getTokenParsers()
    {
        return array(
            new \Ignus\View\TokenParser\ForParser(),
            new \Ignus\View\TokenParser\IfParser(),
            new \Ignus\View\TokenParser\ExtendsParser(),
            new \Ignus\View\TokenParser\IncludeParser(),
            new \Ignus\View\TokenParser\Block(),
            new \Ignus\View\TokenParser\UseParser(),
            new \Ignus\View\TokenParser\Filter(),
            new \Ignus\View\TokenParser\Macro(),
            new \Ignus\View\TokenParser\Import(),
            new \Ignus\View\TokenParser\From(),
            new \Ignus\View\TokenParser\Set(),
            new \Ignus\View\TokenParser\Spaceless(),
        );
    }

    /**
     * @return array
     */
    public function getFilters()
    {
        $filters = array(
            // formatting filters
            'date'    => new FunctionFilter('\Ignus\View\Extension\twig_date_format_filter'),
            'format'  => new FunctionFilter('sprintf'),
            'replace' => new FunctionFilter('twig_strtr'),

            // encoding
            'url_encode'  => new FunctionFilter('twig_urlencode_filter'),
            'json_encode' => new Method($this, 'jsonEncode'),

            // string filters
            'title'      => new FunctionFilter('twig_title_string_filter', array('needs_environment' => true)),
            'capitalize' => new FunctionFilter('twig_capitalize_string_filter', array('needs_environment' => true)),
            'upper'      => new FunctionFilter('strtoupper'),
            'lower'      => new FunctionFilter('strtolower'),
            'striptags'  => new FunctionFilter('strip_tags'),

            // array helpers
            'join'    => new FunctionFilter('twig_join_filter'),
            'reverse' => new FunctionFilter('twig_reverse_filter'),
            'length'  => new FunctionFilter('\Ignus\View\Extension\twig_length_filter', array('needs_environment' => true)),
            'sort'    => new FunctionFilter('twig_sort_filter'),
            'merge'   => new FunctionFilter('twig_array_merge'),

            // iteration and runtime
            'default' => new FunctionFilter('\Ignus\View\Extension\twig_default_filter'),
            'keys'    => new FunctionFilter('twig_get_array_keys_filter'),

            // escaping
            'escape' => new FunctionFilter('\Ignus\View\Extension\twig_escape_filter', array('needs_environment' => true, 'is_safe_callback' => '\Ignus\View\Extension\twig_escape_filter_is_safe')),
            'e'      => new FunctionFilter('\Ignus\View\Extension\twig_escape_filter', array('needs_environment' => true, 'is_safe_callback' => '\Ignus\View\Extension\twig_escape_filter_is_safe')),
        );

        if (function_exists('mb_get_info')) {
            $filters['upper'] = new FunctionFilter('twig_upper_filter', array('needs_environment' => true));
            $filters['lower'] = new FunctionFilter('twig_lower_filter', array('needs_environment' => true));
        }

        return $filters;
    }

    /**
     * @return \Ignus\View\Filter\Method[]
     */
    public function getFunctions()
    {
        return array(
            'range'    => new Func('range'),
            'constant' => new Func('constant'),
            'cycle'    => new \Ignus\View\Functions\Method($this, 'getCycle'),
        );
    }

    public function jsonEncode($value, $options = 0)
    {
        if ($value instanceof Markup) {
            $value = (string) $value;
        }
        elseif (is_array($value)) {
            array_walk_recursive($value, function($value) {
                if ($value instanceof Markup)
                    $value = (string) $value;
                });
        }

        return json_encode($value, $options);
    }

    public function getCycle($values, $i)
    {
        if (!is_array($values) && !($values instanceof \ArrayAccess)) {
            return $values;
        }

        return $values[$i % count($values)];
    }

    /**
     * @return \Ignus\View\Test\FunctionTest[]
     */
    public function getTests()
    {
        return array(
            'even'        => new FunctionTest('\Ignus\View\Extension\twig_test_even'),
            'odd'         => new FunctionTest('\Ignus\View\Extension\twig_test_odd'),
            'defined'     => new FunctionTest('array_key_exists'),
            'sameas'      => new FunctionTest('\Ignus\View\Extension\twig_test_sameas'),
            'none'        => new FunctionTest('\Ignus\View\Extension\twig_test_none'),
            'null'        => new FunctionTest('\Ignus\View\Extension\twig_test_none'),
            'divisibleby' => new FunctionTest('\Ignus\View\Extension\twig_test_divisibleby'),
            'constant'    => new FunctionTest('\Ignus\View\Extension\twig_test_constant'),
            'empty'       => new FunctionTest('\Ignus\View\Extension\twig_test_empty'),
        );
    }

    /**
     * @return array
     */
    public function getOperators()
    {
        return array(
            array(
                'not' => array('precedence' => 50, 'class' => '\Ignus\View\Node\Expression\Unary\Not'),
                '-'   => array('precedence' => 50, 'class' => '\Ignus\View\Node\Expression\Unary\Neg'),
                '+'   => array('precedence' => 50, 'class' => '\Ignus\View\Node\Expression\Unary\Pos'),
            ),
            array(
                'b-and'  => array('precedence' => 5, 'class' => '\Ignus\View\Node\Expression\Binary\BitwiseAnd', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                'b-xor'  => array('precedence' => 5, 'class' => '\Ignus\View\Node\Expression\Binary\BitwiseXor', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                'b-or'   => array('precedence' => 5, 'class' => '\Ignus\View\Node\Expression\Binary\BitwiseOr', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                'or'     => array('precedence' => 10, 'class' => '\Ignus\View\Node\Expression\Binary\OrOp', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                'and'    => array('precedence' => 15, 'class' => '\Ignus\View\Node\Expression\Binary\AndOp', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '=='     => array('precedence' => 20, 'class' => '\Ignus\View\Node\Expression\Binary\Equal', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '!='     => array('precedence' => 20, 'class' => '\Ignus\View\Node\Expression\Binary\NotEqual', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '<'      => array('precedence' => 20, 'class' => '\Ignus\View\Node\Expression\Binary\Less', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '>'      => array('precedence' => 20, 'class' => '\Ignus\View\Node\Expression\Binary\Greater', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '>='     => array('precedence' => 20, 'class' => '\Ignus\View\Node\Expression\Binary\GreaterEqual', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '<='     => array('precedence' => 20, 'class' => '\Ignus\View\Node\Expression\Binary\LessEqual', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                'not in' => array('precedence' => 20, 'class' => '\Ignus\View\Node\Expression\Binary\NotIn', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                'in'     => array('precedence' => 20, 'class' => '\Ignus\View\Node\Expression\Binary\In', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '+'      => array('precedence' => 30, 'class' => '\Ignus\View\Node\Expression\Binary\Add', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '-'      => array('precedence' => 30, 'class' => '\Ignus\View\Node\Expression\Binary\Sub', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '~'      => array('precedence' => 40, 'class' => '\Ignus\View\Node\Expression\Binary\Concat', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '*'      => array('precedence' => 60, 'class' => '\Ignus\View\Node\Expression\Binary\Mul', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '/'      => array('precedence' => 60, 'class' => '\Ignus\View\Node\Expression\Binary\Div', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '//'     => array('precedence' => 60, 'class' => '\Ignus\View\Node\Expression\Binary\FloorDiv', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '%'      => array('precedence' => 60, 'class' => '\Ignus\View\Node\Expression\Binary\Mod', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                'is'     => array('precedence' => 100, 'callable' => array($this, 'parseTestExpression'), 'associativity' => ExpressionParser::OPERATOR_LEFT),
                'is not' => array('precedence' => 100, 'callable' => array($this, 'parseNotTestExpression'), 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '..'     => array('precedence' => 110, 'class' => '\Ignus\View\Node\Expression\Binary\Range', 'associativity' => ExpressionParser::OPERATOR_LEFT),
                '**'     => array('precedence' => 200, 'class' => '\Ignus\View\Node\Expression\Binary\Power', 'associativity' => ExpressionParser::OPERATOR_RIGHT),
            ),
        );
    }

    public function parseNotTestExpression(Parser $parser, $node)
    {
        return new \Ignus\View\Node\Expression\Unary\Not($this->parseTestExpression($parser, $node), $parser->getCurrentToken()->getLine());
    }

    public function parseTestExpression(Parser $parser, $node)
    {
        $stream = $parser->getStream();
        $name = $stream->expect(Token::NAME_TYPE);
        $arguments = null;
        if ($stream->test(Token::PUNCTUATION_TYPE, '(')) {
            $arguments = $parser->getExpressionParser()->parseArguments();
        }

        return new Test($node, $name->getValue(), $arguments, $parser->getCurrentToken()->getLine());
    }

    public function getName()
    {
        return 'core';
    }
}

function twig_date_format_filter($date, $format = 'F j, Y H:i', $timezone = null)
{
    if (!$date instanceof \DateTime && !$date instanceof \DateInterval) {
        $date = new \DateTime((ctype_digit($date) ? '@' : '').$date);
    }

    if (null !== $timezone) {
        if (!$timezone instanceof \DateTimeZone) {
            $timezone = new \DateTimeZone($timezone);
        }
        $date->setTimezone($timezone);
    }

    return $date->format($format);
}

function twig_urlencode_filter($url, $raw = false)
{
    if ($raw) {
        return rawurlencode($url);
    }

    return urlencode($url);
}

function twig_array_merge($arr1, $arr2)
{
    if (!is_array($arr1) || !is_array($arr2)) {
        throw new Runtime('The merge filter only work with arrays or hashes.');
    }

    return array_merge($arr1, $arr2);
}

function twig_join_filter($value, $glue = '')
{
    return implode($glue, (array) $value);
}

function twig_default_filter($value, $default = '')
{
    return twig_test_empty($value) ? $default : $value;
}

function twig_get_array_keys_filter($array)
{
    if (is_object($array) && $array instanceof \Traversable) {
        return array_keys(iterator_to_array($array));
    }

    if (!is_array($array)) {
        return array();
    }

    return array_keys($array);
}

function twig_reverse_filter($array)
{
    if (is_object($array) && $array instanceof \Traversable) {
        return array_reverse(iterator_to_array($array));
    }

    if (!is_array($array)) {
        return array();
    }

    return array_reverse($array);
}

function twig_sort_filter($array)
{
    asort($array);

    return $array;
}

function twig_in_filter($value, $compare)
{
    if (is_array($compare)) {
        return in_array($value, $compare);
    } elseif (is_string($compare)) {
        return false !== strpos($compare, (string) $value);
    } elseif (is_object($compare) && $compare instanceof \Traversable) {
        return in_array($value, iterator_to_array($compare, false));
    }

    return false;
}

function twig_strtr($pattern, $replacements)
{
    return str_replace(array_keys($replacements), array_values($replacements), $pattern);
}

function twig_escape_filter(Environment $env, $string, $type = 'html', $charset = null, $autoescape = false)
{
    if ($autoescape && is_object($string) && $string instanceof Markup) {
        return $string;
    }

    if (!is_string($string) && !(is_object($string) && method_exists($string, '__toString'))) {
        return $string;
    }

    if (null === $charset) {
        $charset = $env->getCharset();
    }

    switch ($type) {
        case 'js':
            // escape all non-alphanumeric characters
            // into their \xHH or \uHHHH representations
            if ('UTF-8' != $charset) {
                $string = _twig_convert_encoding($string, 'UTF-8', $charset);
            }

            if (null === $string = preg_replace_callback('#[^\p{L}\p{N} ]#u', '_twig_escape_js_callback', $string)) {
                throw new Runtime('The string to escape is not a valid UTF-8 string.');
            }

            if ('UTF-8' != $charset) {
                $string = _twig_convert_encoding($string, $charset, 'UTF-8');
            }

            return $string;

        case 'html':
            return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset);

        default:
            throw new Runtime(sprintf('Invalid escape type "%s".', $type));
    }
}

function twig_escape_filter_is_safe(Node $filterArgs)
{
    foreach ($filterArgs as $arg) {
        /** @var \Ignus\View\Node $arg */
        if ($arg instanceof Constant) {
            return array($arg->getAttribute('value'));
        } else {
            return array();
        }

        break;
    }

    return array('html');
}

if (function_exists('iconv')) {
    function _twig_convert_encoding($string, $to, $from)
    {
        return iconv($from, $to, $string);
    }
} elseif (function_exists('mb_convert_encoding')) {
    function _twig_convert_encoding($string, $to, $from)
    {
        return mb_convert_encoding($string, $to, $from);
    }
} else {
    function _twig_convert_encoding($string, $to, $from)
    {
        throw new Runtime('No suitable convert encoding function (use UTF-8 as your encoding or install the iconv or mbstring extension).');
    }
}

function _twig_escape_js_callback($matches)
{
    $char = $matches[0];

    // \xHH
    if (!isset($char[1])) {
        return '\\x'.substr('00'.bin2hex($char), -2);
    }

    // \uHHHH
    $char = _twig_convert_encoding($char, 'UTF-16BE', 'UTF-8');

    return '\\u'.substr('0000'.bin2hex($char), -4);
}

if (function_exists('mb_get_info')) {
    function twig_length_filter(Environment $env, $thing)
    {
        return is_scalar($thing) ? mb_strlen($thing, $env->getCharset()) : count($thing);
    }

    function twig_upper_filter(Environment $env, $string)
    {
        if (null !== ($charset = $env->getCharset())) {
            return mb_strtoupper($string, $charset);
        }

        return strtoupper($string);
    }

    function twig_lower_filter(Environment $env, $string)
    {
        if (null !== ($charset = $env->getCharset())) {
            return mb_strtolower($string, $charset);
        }

        return strtolower($string);
    }

    function twig_title_string_filter(Environment $env, $string)
    {
        if (null !== ($charset = $env->getCharset())) {
            return mb_convert_case($string, MB_CASE_TITLE, $charset);
        }

        return ucwords(strtolower($string));
    }

    function twig_capitalize_string_filter(Environment $env, $string)
    {
        if (null !== ($charset = $env->getCharset())) {
            return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).
                         mb_strtolower(mb_substr($string, 1, mb_strlen($string, $charset), $charset), $charset);
        }

        return ucfirst(strtolower($string));
    }
}
// and byte fallback
else
{
    function twig_length_filter(Environment $env, $thing)
    {
        return is_scalar($thing) ? strlen($thing) : count($thing);
    }

    function twig_title_string_filter(Environment $env, $string)
    {
        return ucwords(strtolower($string));
    }

    function twig_capitalize_string_filter(Environment $env, $string)
    {
        return ucfirst(strtolower($string));
    }
}

function twig_ensure_traversable($seq)
{
    if (is_array($seq) || (is_object($seq) && $seq instanceof \Traversable)) {
        return $seq;
    }
    else {
        return array();
    }
}

function twig_test_sameas($value, $test)
{
    return $value === $test;
}

function twig_test_none($value)
{
    return null === $value;
}

function twig_test_divisibleby($value, $num)
{
    return 0 == $value % $num;
}

function twig_test_even($value)
{
    return $value % 2 == 0;
}

function twig_test_odd($value)
{
    return $value % 2 == 1;
}

function twig_test_constant($value, $constant)
{
    return constant($constant) === $value;
}

function twig_test_empty($value)
{
    if ($value instanceof \Countable) {
        return 0 == count($value);
    }
    return false === $value || (empty($value) && '0' != $value);
}
